package com.bsj.media.media.G726;

public class G726_common {
	static final int qtab_726_16[] = { 261 };

	static final int qtab_726_24[] = { 8, 218, 331 };

	static final int qtab_726_32[] = { -124, 80, 178, 246, 300, 349, 400 };

	static final int qtab_726_40[] = { -122, -16, 68, 139, 198, 250, 298, 339, 378, 413, 445, 475, 502, 528, 553 };

	/*
	 * Maps G.726_16 code word to reconstructed scale factor normalized log
	 * magnitude values.
	 */
	static final int g726_16_dqlntab[] = { // 4
			116, 365, 365, 116 };

	/* Maps G.726_16 code word to log of scale factor multiplier. */
	static final int g726_16_witab[] = { // 4
			-704, 14048, 14048, -704 };

	/*
	 * Maps G.726_16 code words to a set of values whose long and short term
	 * averages are computed and then compared to give an indication how stationary
	 * (steady state) the signal is.
	 */
	static final int g726_16_fitab[] = { // 4
			0x000, 0xE00, 0xE00, 0x000 };

	/*
	 * Maps G.726_24 code word to reconstructed scale factor normalized log
	 * magnitude values.
	 */
	static final int g726_24_dqlntab[] = { // 8
			-2048, 135, 273, 373, 373, 273, 135, -2048 };

	/* Maps G.726_24 code word to log of scale factor multiplier. */
	static final int g726_24_witab[] = { // 8
			-128, 960, 4384, 18624, 18624, 4384, 960, -128 };

	/*
	 * Maps G.726_24 code words to a set of values whose long and short term
	 * averages are computed and then compared to give an indication how stationary
	 * (steady state) the signal is.
	 */
	static final int g726_24_fitab[] = { // 8
			0x000, 0x200, 0x400, 0xE00, 0xE00, 0x400, 0x200, 0x000 };

	/*
	 * Maps G.726_32 code word to reconstructed scale factor normalized log
	 * magnitude values.
	 */
	static final int g726_32_dqlntab[] = { // 16
			-2048, 4, 135, 213, 273, 323, 373, 425, 425, 373, 323, 273, 213, 135, 4, -2048 };

	/* Maps G.726_32 code word to log of scale factor multiplier. */
	static final int g726_32_witab[] = { // 16
			-384, 576, 1312, 2048, 3584, 6336, 11360, 35904, 35904, 11360, 6336, 3584, 2048, 1312, 576, -384
	};

	/*
	 * Maps G.726_32 code words to a set of values whose long and short term
	 * averages are computed and then compared to give an indication how stationary
	 * (steady state) the signal is.
	 */
	static final int g726_32_fitab[] = { // 16
			0x000, 0x000, 0x000, 0x200, 0x200, 0x200, 0x600, 0xE00, 0xE00, 0x600, 0x200, 0x200, 0x200, 0x000, 0x000,
			0x000 };

	/*
	 * Maps G.726_40 code word to ructeconstructed scale factor normalized log
	 * magnitude values.
	 */
	static final int g726_40_dqlntab[] = { // 32
			-2048, -66, 28, 104, 169, 224, 274, 318, 358, 395, 429, 459, 488, 514, 539, 566, 566, 539, 514, 488, 459,
			429, 395, 358, 318, 274, 224, 169, 104, 28, -66, -2048 };

	/* Maps G.726_40 code word to log of scale factor multiplier. */
	static final int g726_40_witab[] = { // 32
			448, 448, 768, 1248, 1280, 1312, 1856, 3200, 4512, 5728, 7008, 8960, 11456, 14080, 16928, 22272, 22272,
			16928, 14080, 11456, 8960, 7008, 5728, 4512, 3200, 1856, 1312, 1280, 1248, 768, 448, 448 };

	/*
	 * Maps G.726_40 code words to a set of values whose long and short term
	 * averages are computed and then compared to give an indication how stationary
	 * (steady state) the signal is.
	 */
	static final int g726_40_fitab[] = { // 32
			0x000, 0x000, 0x000, 0x000, 0x000, 0x200, 0x200, 0x200, 0x200, 0x200, 0x400, 0x600, 0x800, 0xA00, 0xC00,
			0xC00, 0xC00, 0xC00, 0xA00, 0x800, 0x600, 0x400, 0x200, 0x200, 0x200, 0x200, 0x200, 0x000, 0x000, 0x000,
			0x000, 0x000 };

	public static int top_bit(int bits) {
		int res;

		if (bits == 0)
			return -1;
		res = 0;
		if ((bits & 0xFFFF0000) != 0) {
			bits &= 0xFFFF0000;
			res += 16;
		}
		if ((bits & 0xFF00FF00) != 0) {
			bits &= 0xFF00FF00;
			res += 8;
		}
		if ((bits & 0xF0F0F0F0) != 0) {
			bits &= 0xF0F0F0F0;
			res += 4;
		}
		if ((bits & 0xCCCCCCCC) != 0) {
			bits &= 0xCCCCCCCC;
			res += 2;
		}
		if ((bits & 0xAAAAAAAA) != 0) {
			bits &= 0xAAAAAAAA;
			res += 1;
		}
		return res;
	}

	public static bitstream_state_s bitstream_init(bitstream_state_s s) {
		if (s == null)
			return null;
		s.setBitstream(0);
		s.setResidue(0);
		return s;
	}

	/*
	 * Given a raw sample, 'd', of the difference signal and a quantization step
	 * size scale factor, 'y', this routine returns the ADPCM codeword to which that
	 * sample gets quantized. The step size scale factor division operation is done
	 * in the log base 2 domain as a subtraction.
	 */
	public static short quantize(int d, /* Raw difference signal sample */
			int y, /* Step size multiplier */
			final int table[], /* quantization table */
			int quantizer_states) /* table size of short integers */
	{
		short dqm; /* Magnitude of 'd' */
		short exp; /* Integer part of base 2 log of 'd' */
		short mant; /* Fractional part of base 2 log */
		short dl; /* Log of magnitude of 'd' */
		short dln; /* Step size scale factor normalized log */
		int i;
		int size;

		/*
		 * LOG
		 *
		 * Compute base 2 log of 'd', and store in 'dl'.
		 */
		dqm = (short) Math.abs(d);
		exp = (short) (top_bit(dqm >> 1) + 1);
		/* Fractional portion. */
		mant = (short) (((dqm << 7) >> exp) & 0x7F);
		dl = (short) ((exp << 7) + mant);

		/*
		 * SUBTB
		 *
		 * "Divide" by step size multiplier.
		 */
		dln = (short) (dl - (short) (y >> 2));

		/*
		 * QUAN
		 *
		 * Search for codword i for 'dln'.
		 */
		size = (quantizer_states - 1) >> 1;
		for (i = 0; i < size; i++) {
			if (dln < table[i])
				break;
		}
		if (d < 0) {
			/* Take 1's complement of i */
			return (short) ((size << 1) + 1 - i);
		}
		if (i == 0 && (quantizer_states & 1) != 0) {
			/*
			 * Zero is only valid if there are an even number of states, so take the 1's
			 * complement if the code is zero.
			 */
			return (short) quantizer_states;
		}
		return (short) i;
	}

	/*
	 * returns the integer product of the 14-bit integer "an" and "floating point"
	 * representation (4-bit exponent, 6-bit mantessa) "srn".
	 */
	public static short fmult(short an, short srn) {
		short anmag;
		short anexp;
		short anmant;
		short wanexp;
		short wanmant;
		short retval;

		anmag = (short) ((an > 0) ? an : ((-an) & 0x1FFF));
		anexp = (short) (top_bit(anmag) - 5);
		anmant = (short) ((anmag == 0) ? 32 : (anexp >= 0) ? (anmag >> anexp) : (anmag << -anexp));
		wanexp = (short) (anexp + ((srn >> 6) & 0xF) - 13);

		wanmant = (short) ((anmant * (srn & 0x3F) + 0x30) >> 4);
		retval = (short) ((wanexp >= 0) ? ((wanmant << wanexp) & 0x7FFF) : (wanmant >> -wanexp));

		return (short) (((an ^ srn) < 0) ? -retval : retval);
	}

	/*
	 * Compute the estimated signal from the 6-zero predictor.
	 */
	public static short predictor_zero(g726_state_s s) {
		int i;
		int sezi;

		sezi = fmult((short) (s.getB()[0] >> 2), s.getDq()[0]);
		/* ACCUM */
		for (i = 1; i < 6; i++) {
			sezi += fmult((short) (s.getB()[i] >> 2), s.getDq()[i]);
		}
		return (short) sezi;
	}

	/*
	 * Computes the estimated signal from the 2-pole predictor.
	 */
	public static short predictor_pole(g726_state_s s) {
		return (short) (fmult((short) (s.getA()[1] >> 2), s.getSr()[1])
				+ fmult((short) (s.getA()[0] >> 2), s.getSr()[0]));
	}

	/*
	 * Computes the quantization step size of the adaptive quantizer.
	 */
	public static int step_size(g726_state_s s) {
		int y;
		int dif;
		int al;

		if (s.getAp() >= 256) {
			return s.getYu();
		}
		y = s.getYl() >> 6;
		dif = s.getYu() - y;
		al = s.getAp() >> 2;
		if (dif > 0)
			y += (dif * al) >> 6;
		else if (dif < 0)
			y += (dif * al + 0x3F) >> 6;
		return y;
	}

	/*
	 * Returns reconstructed difference signal 'dq' obtained from codeword 'i' and
	 * quantization step size scale factor 'y'. Multiplication is performed in log
	 * base 2 domain as addition.
	 */
	public static short reconstruct(int sign, /* 0 for non-negative value */
			int dqln, /* G.72x codeword */
			int y) /* Step size multiplier */
	{
		short dql; /* Log of 'dq' magnitude */
		short dex; /* Integer part of log */
		short dqt;
		short dq; /* Reconstructed difference signal sample */

		dql = (short) (dqln + (y >> 2)); /* ADDA */

		if (dql < 0) {
			return (short) ((sign != 0) ? -0x8000 : 0);
		}
		/* ANTILOG */
		dex = (short) ((dql >> 7) & 15);
		dqt = (short) (128 + (dql & 127));
		dq = (short) ((dqt << 7) >> (14 - dex));
		return (short) ((sign != 0) ? (dq - 0x8000) : dq);
	}

	/*
	 * updates the state variables for each output code
	 */
	public static void update(g726_state_s s, int y, /* quantizer step size */
			int wi, /* scale factor multiplier */
			int fi, /* for long/short term energies */
			int dq, /* quantized prediction difference */
			int sr, /* reconstructed signal */
			int dqsez) /* difference from 2-pole predictor */
	{
		short mag;
		short exp;
		short a2p; /* LIMC */
		short a1ul; /* UPA1 */
		short pks1; /* UPA2 */
		short fa1;
		short ylint;
		short dqthr;
		short ylfrac;
		short thr;
		short pk0;
		int i;
		int tr;

		a2p = 0;
		/* Needed in updating predictor poles */
		pk0 = (short) ((dqsez < 0) ? 1 : 0);

		/* prediction difference magnitude */
		mag = (short) (dq & 0x7FFF);
		/* TRANS */
		ylint = (short) (s.getYl() >> 15); /* exponent part of yl */
		ylfrac = (short) ((s.getYl() >> 10) & 0x1F); /* fractional part of yl */
		/* Limit threshold to 31 << 10 */
		thr = (short) ((ylint > 9) ? (31 << 10) : ((32 + ylfrac) << ylint));
		dqthr = (short) ((thr + (thr >> 1)) >> 1); /* dqthr = 0.75 * thr */
		if (s.getTd() == 0) { /* signal supposed voice */
			tr = 0;
		} else if (mag <= dqthr) { /* supposed data, but small mag */
			tr = 0;
		} /* treated as voice */
		else { /* signal is data (modem) */
			tr = 1;
		}

		/*
		 * Quantizer scale factor adaptation.
		 */

		/* FUNCTW & FILTD & DELAY */
		/* update non-steady state step size multiplier */
		s.setYu((short) (y + ((wi - y) >> 5)));

		/* LIMB */
		if (s.getYu() < 544) {
			s.setYu((short) 544);
		} else if (s.getYu() > 5120) {
			s.setYu((short) 5120);
		}

		/* FILTE & DELAY */
		/* update steady state step size multiplier */
		int tempYl = s.getYl();
		tempYl += s.getYu() + ((-tempYl) >> 6);
		s.setYl(tempYl);
		/*
		 * Adaptive predictor coefficients.
		 */
		if (tr != 0) {
			/* Reset the a's and b's for a modem signal */
			s.getA()[0] = 0;
			s.getA()[1] = 0;
			s.getB()[0] = 0;
			s.getB()[1] = 0;
			s.getB()[2] = 0;
			s.getB()[3] = 0;
			s.getB()[4] = 0;
			s.getB()[5] = 0;
		} else {
			/* Update the a's and b's */
			/* UPA2 */
			pks1 = (short) (pk0 ^ s.getPk()[0]);

			/* Update predictor pole a[1] */
			a2p = (short) (s.getA()[1] - (s.getA()[1] >> 7));
			if (dqsez != 0) {
				if (pks1 != 0) {
					fa1 = s.getA()[0];
				} else {
					fa1 = (short) -s.getA()[0];
				}
				/* a2p = function of fa1 */
				if (fa1 < -8191) {
					a2p -= 0x100;
				} else if (fa1 > 8191) {
					a2p += 0xFF;
				} else {
					a2p += fa1 >> 5;
				}

				if ((pk0 ^ s.getPk()[1]) != 0) {
					/* LIMC */
					if (a2p <= -12160) {
						a2p = -12288;
					} else if (a2p >= 12416) {
						a2p = 12288;
					} else {
						a2p -= 0x80;
					}
				} else if (a2p <= -12416) {
					a2p = -12288;
				} else if (a2p >= 12160) {
					a2p = 12288;
				} else {
					a2p += 0x80;
				}
			}

			/* TRIGB & DELAY */
			s.getA()[1] = a2p;

			/* UPA1 */
			/* Update predictor pole a[0] */
			s.getA()[0] -= (s.getA()[0] >> 8);
			if (dqsez != 0) {
				if (pks1 == 0) {
					s.getA()[0] += 192;
				} else {
					s.getA()[0] -= 192;
				}
			}
			/* LIMD */
			a1ul = (short) (15360 - a2p);
			if (s.getA()[0] < -a1ul) {
				s.getA()[0] = (short) -a1ul;
			} else if (s.getA()[0] > a1ul) {
				s.getA()[0] = a1ul;
			}
			/* UPB : update predictor zeros b[6] */
			for (i = 0; i < 6; i++) {
				/* Distinguish 40Kbps mode from the others */
				s.getB()[i] -= s.getB()[i] >> ((s.getBits_per_sample() == 5) ? 9 : 8);
				if ((dq & 0x7FFF) != 0) {
					/* XOR */
					if ((dq ^ s.getDq()[i]) >= 0) {
						s.getB()[i] += 128;
					} else {
						s.getB()[i] -= 128;
					}
				}
			}
		}

		for (i = 5; i > 0; i--) {
			s.getDq()[i] = s.getDq()[i - 1];
		}
		/* FLOAT A : convert dq[0] to 4-bit exp, 6-bit mantissa f.p. */
		if (mag == 0) {
			if (dq >= 0) {
				s.getDq()[0] = 0x20;
			} else {
				s.getDq()[0] = (short) 0xFC20;
			}
		} else {
			exp = (short) (top_bit(mag) + 1);
			if (dq >= 0) {
				s.getDq()[0] = (short) ((exp << 6) + ((mag << 6) >> exp));
			} else {
				s.getDq()[0] = (short) ((exp << 6) + ((mag << 6) >> exp) - 0x400);
			}
		}

		s.getSr()[1] = s.getSr()[0];
		/* FLOAT B : convert sr to 4-bit exp., 6-bit mantissa f.p. */
		if (sr == 0) {
			s.getSr()[0] = 0x20;
		} else if (sr > 0) {
			exp = (short) (top_bit(sr) + 1);
			s.getSr()[0] = (short) ((exp << 6) + ((sr << 6) >> exp));
		} else if (sr > -32768) {
			mag = (short) -sr;
			exp = (short) (top_bit(mag) + 1);
			s.getSr()[0] = (short) ((exp << 6) + ((mag << 6) >> exp) - 0x400);
		} else {
			s.getSr()[0] = (short) 0xFC20;
		}

		/* DELAY A */
		s.getPk()[1] = s.getPk()[0];
		s.getPk()[0] = pk0;

		/* TONE */
		if (tr != 0) { /* this sample has been treated as data */
			s.setTd(0);
		} /* next one will be treated as voice */
		else if (a2p < -11776) { /* small sample-to-sample correlation */
			s.setTd(1); /* signal may be data */
		} else { /* signal is voice */
			s.setTd(0);
		}
		/* Adaptation speed control. */
		short temp = s.getDms();
		/* FILTA */
		temp += ((short) fi - s.getDms()) >> 5;
		s.setDms(temp);
		/* FILTB */
		temp = s.getDml();
		temp += ((short) ((fi << 2) - s.getDml()) >> 7);
		s.setDml(temp);

		temp = s.getAp();

		if (tr != 0) {
			s.setAp((short) 256);
		} else if (y < 1536) { /* SUBTC */
			temp += (0x200 - s.getAp()) >> 4;
		} else if (s.getTd() != 0) {
			temp += ((0x200 - temp) >> 4);
		} else if (Math.abs((s.getDms() << 2) - s.getDml()) >= (s.getDml() >> 3)) {
			temp += ((0x200 - temp) >> 4);
		} else {
			temp += (-temp) >> 4;
		}
		s.setAp(temp);
	}
}
